package com.test.servicedemo;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "htz_test";

    private Button startButton;
    private Button endButton;

    private Button bing;
    private Button unBind;
    private Button getServiceState;


    private MyService.MyBinder binder;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e(TAG, "onServiceConnected: " + "service connected" );
            binder = (MyService.MyBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(TAG, "onServiceConnected: " + "service Disconnected" );
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startButton = findViewById(R.id.start);
        endButton = findViewById(R.id.end);
        bing = findViewById(R.id.bind);
        unBind = findViewById(R.id.unbind);
        getServiceState = findViewById(R.id.service_state);

        startButton.setOnClickListener(this);
        endButton.setOnClickListener(this);
        bing.setOnClickListener(this);
        unBind.setOnClickListener(this);
        getServiceState.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        Intent intent =  new Intent(this,MyService.class);
        switch (v.getId()){
            case R.id.start:
                startService(intent);
                break;
            case R.id.end:
                stopService(intent);
                break;

            case R.id.bind:
                bindService(intent, connection , Service.BIND_AUTO_CREATE);
                break;

            case R.id.unbind:
                unbindService(connection);
                break;

            case R.id.service_state:
                Log.e(TAG, "onClick: service 的 count的值为 " + binder.getCount() );
                break;
        }
    }
}